package hust.iamk.settings;

import group.pals.android.lib.ui.lockpattern.LockPatternActivity;
import hust.iamk.backup.Constants;
import hust.iamk.backup.Directory;
import hust.iamk.backup.NetworkUtil;
import hust.iamk.backup.ServiceBackup;

import java.io.File;
import java.io.FileOutputStream;

import org.wordpress.passcodelock.AppLockManager;
import org.wordpress.passcodelock.PasscodeManagePasswordActivity;

import android.accounts.AccountManager;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import com.cooliris.media.LocalDataSource;
import com.hust.iamk.R;

public class SettingsActivity extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {
	public static final int REQ_LOGIN_PATTERN = 11;
	public static final int REQ_CREATE_PATTERN = 12;
	public static final int REQ_CHANGE_PATTERN = 13;
	public static final int REQ_CLEAR_PATTERN = 14;

	public static final int LOGIN_PASSLOCK = 20;
	public static final int ENABLE_PASSLOCK = 21;
	public static final int DISABLE_PASSLOCK = 22;
	public static final int CHANGE_PASSWORD = 23;
	
	private static final String ANIMATION_SPEED_PREFERENCE_KEY = "animation_speed";

	private CheckBoxPreference mCheckLockFolder = null;
	private ListPreference mListLockType = null;
	private Preference turnPassOnOff = null;
	private Preference changePass = null;
	private Preference forgotPass = null;
	private CheckBoxPreference mCheckSyncContents = null;
	private CheckBoxPreference mCheckAutoRotate = null;
	private CheckBoxPreference mCheckThickAlbumBorder = null;
	private CheckBoxPreference mCheckNotificationBar = null;
	private CheckBoxPreference mCheckCameraButton = null;
	private CheckBoxPreference mCheckScalingButtons = null;
	private CheckBoxPreference mCheckCacheThumbnails = null;
	private CheckBoxPreference mCheckDefaultPlayer = null;
	private CheckBoxPreference mCheckCompactShareMenu = null;
	private Context mContext;

	
	public static char[] savedPattern;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		if (android.os.Build.VERSION.SDK_INT >= 11) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
		addPreferencesFromResource(R.xml.settings);
		mContext = this;
		mCheckLockFolder = (CheckBoxPreference) findPreference("show_lock_folder");
		mListLockType = (ListPreference) findPreference("lock_type");
		turnPassOnOff = (Preference) findPreference("turn_pass_on_off");
		changePass = (Preference) findPreference("change_pass");
		forgotPass = (Preference) findPreference("forgot_pass");

		if (!mCheckLockFolder.isChecked()) {
			turnPassOnOff.setEnabled(false);
			changePass.setEnabled(false);
			forgotPass.setEnabled(false);
		} else {
			updateUI();
		}

		mCheckLockFolder.setOnPreferenceChangeListener(checkShowLockFolderListener);
		mListLockType.setOnPreferenceChangeListener(chooseLockTypeListener);
		turnPassOnOff.setOnPreferenceClickListener(passOnOffTouchListener);
		changePass.setOnPreferenceClickListener(changePassTouchListener);
		mCheckSyncContents = (CheckBoxPreference) findPreference("show_sync_contents");
		mCheckSyncContents.setOnPreferenceChangeListener(checkSyncContentsChangeListener);

		mCheckAutoRotate = (CheckBoxPreference) findPreference("auto_rotate_sccreen");
		mCheckThickAlbumBorder = (CheckBoxPreference) findPreference("thick_album");
		mCheckNotificationBar = (CheckBoxPreference) findPreference("notifications_bar");
		mCheckCameraButton = (CheckBoxPreference) findPreference("camera_button");
		mCheckScalingButtons = (CheckBoxPreference) findPreference("scaling_button");
		mCheckCacheThumbnails = (CheckBoxPreference) findPreference("cache_thumbnails");
		mCheckDefaultPlayer = (CheckBoxPreference) findPreference("default_player");
		mCheckCompactShareMenu = (CheckBoxPreference) findPreference("compact_share");

		getPreferenceScreen().getSharedPreferences()
				.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		mCheckSyncContents.setChecked(false);
		super.onResume();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// ignore orientation change
		super.onConfigurationChanged(newConfig);
	}

	OnPreferenceClickListener passOnOffTouchListener = new OnPreferenceClickListener() {
		@Override
		public boolean onPreferenceClick(Preference preference) {
			int type = AppLockManager.getInstance().getCurrentAppLock().isPasswordLocked() ? DISABLE_PASSLOCK : ENABLE_PASSLOCK;
			int typePattern = AppLockManager.getInstance().getCurrentAppLock().isPatternLocked() ? DISABLE_PASSLOCK : ENABLE_PASSLOCK;
			Log.d("pref", "Turn on/off password - type: " + type + " disable: "	+ DISABLE_PASSLOCK + " enable: " + ENABLE_PASSLOCK);
			if (mListLockType.getValue().toString().equals("1")) {
				Intent i = new Intent(SettingsActivity.this,PasscodeManagePasswordActivity.class);
				i.putExtra("type", type);
				startActivityForResult(i, type);
			} else {
				// Pattern
				if (typePattern == 1) {
					Intent iChangePattern = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,mContext, LockPatternActivity.class);
					iChangePattern.putExtra(LockPatternActivity.EXTRA_PATTERN, savedPattern);
					iChangePattern.putExtra(LockPatternActivity.EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN, new Intent(mContext, LockPatternActivity.class));
					startActivityForResult(iChangePattern, REQ_CLEAR_PATTERN);
				} else {
					Intent iCreate = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null,mContext, LockPatternActivity.class);
					startActivityForResult(iCreate, REQ_CREATE_PATTERN);
				}
			}
			return false;
		}
	};

	private OnPreferenceClickListener changePassTouchListener = new OnPreferenceClickListener() {
		@Override
		public boolean onPreferenceClick(Preference preference) {
			if (mListLockType.getValue().toString().equals("1")) {
				// Passcode
				Intent iChangePasscode = new Intent(SettingsActivity.this,PasscodeManagePasswordActivity.class);
				iChangePasscode.putExtra("type", CHANGE_PASSWORD);
				iChangePasscode.putExtra("message",getString(R.string.passcode_enter_old_passcode));
				startActivityForResult(iChangePasscode, CHANGE_PASSWORD);
			} else {
				// Pattern
				Intent iChangePattern = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,mContext, LockPatternActivity.class);
				iChangePattern.putExtra(LockPatternActivity.EXTRA_PATTERN,savedPattern);
				iChangePattern.putExtra(LockPatternActivity.EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN, new Intent(mContext, LockPatternActivity.class));
				startActivityForResult(iChangePattern, REQ_CHANGE_PATTERN);
			}
			return false;
		}
	};

	private OnPreferenceChangeListener checkShowLockFolderListener = new OnPreferenceChangeListener() {

		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			if (newValue.toString().equals("true")) {
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.folder_lock);
				File mLockFolder = new File(LocalDataSource.LOCK_BUCKET_FOLDER);
				if(!mLockFolder.exists()){
					mLockFolder.mkdir();
		    	}
				File file = new File(mLockFolder, "folder_lock.jpg");

				FileOutputStream outStream;
				try {
					outStream = new FileOutputStream(file);
					bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
					outStream.flush();
					outStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
//				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"	+ LocalDataSource.LOCK_BUCKET_FOLDER)));
				MediaScannerConnection.scanFile(mContext,
						new String[] { file.getAbsolutePath() }, null,
						new OnScanCompletedListener() {
							@Override
							public void onScanCompleted(String path, Uri uri) {
								Log.d("MediaScanWork", "file " + path + " was scanned seccessfully: " + uri);
							}
						});
				
				
				Log.d("pref", "Change true, app locked: " + AppLockManager.getInstance().getCurrentAppLock().isPasswordLocked());
				if (mListLockType.getValue().toString().equals("1")) {
					if (AppLockManager.getInstance().getCurrentAppLock().isPasswordLocked()) {
						turnPassOnOff.setEnabled(true);
						turnPassOnOff.setTitle(R.string.passcode_turn_off);
						turnPassOnOff.setSummary(R.string.passcode_turn_off_summary);
						changePass.setEnabled(true);
						forgotPass.setEnabled(true);
					} else {
						turnPassOnOff.setEnabled(true);
						turnPassOnOff.setTitle(R.string.passcode_turn_on);
						turnPassOnOff.setSummary(R.string.passcode_turn_on_summary);
						changePass.setEnabled(false);
						forgotPass.setEnabled(false);
					}
				} else {
					if (AppLockManager.getInstance().getCurrentAppLock().isPatternLocked()) {
						turnPassOnOff.setEnabled(true);
						turnPassOnOff.setTitle(R.string.pattern_turn_off);
						turnPassOnOff.setSummary(R.string.pattern_turn_off_summary);
						changePass.setEnabled(true);
						forgotPass.setEnabled(true);
					} else {
						turnPassOnOff.setEnabled(true);
						turnPassOnOff.setTitle(R.string.pattern_turn_on);
						turnPassOnOff.setSummary(R.string.pattern_turn_on_summary);
						changePass.setEnabled(false);
						forgotPass.setEnabled(false);
					}
				}

			} else {
				File file = new File(LocalDataSource.LOCK_BUCKET_FOLDER + "/"	+ "folder_lock.jpg");
				if(file.exists()){
					file.delete();
					ContentResolver resolver = mContext.getContentResolver();
					resolver.delete(Images.Media.EXTERNAL_CONTENT_URI,  Images.Media.DATA +  " = ? ", new String[]{file.getAbsolutePath()});  
				}
					
//				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + LocalDataSource.LOCK_BUCKET_FOLDER)));

				Log.d("pref", "Change false, app locked: " + AppLockManager.getInstance().getCurrentAppLock().isPasswordLocked());
				turnPassOnOff.setEnabled(false);
				changePass.setEnabled(false);
				forgotPass.setEnabled(false);
			}
			return true;
		}
	};

	private OnPreferenceChangeListener chooseLockTypeListener = new OnPreferenceChangeListener() {

		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			Log.d("pref", "List Lock type: " + newValue);
			mListLockType.setValue(String.valueOf(newValue));
			if (newValue.toString().equals("1")) {
				updateUI();
			} else {
				updateUI();
			}
			return true;
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("pref", "Activity Result: request code: " + requestCode + "/ result code: " + resultCode);
		switch (requestCode) {
		case DISABLE_PASSLOCK:
			break;
		case ENABLE_PASSLOCK:
			break;
		case CHANGE_PASSWORD:
			if (resultCode == RESULT_OK) {
				Toast.makeText(SettingsActivity.this, getString(R.string.passcode_set), Toast.LENGTH_SHORT).show();
			}
			break;
		case REQ_CREATE_PATTERN:
			if (resultCode == RESULT_OK) {
				savedPattern = data.getCharArrayExtra(LockPatternActivity.EXTRA_PATTERN);
				AppLockManager.getInstance().getCurrentAppLock()
						.setPattern(String.valueOf(savedPattern));
				Log.d("pref", "pattern: " + String.valueOf(savedPattern));
			}
			break;
		case REQ_CHANGE_PATTERN:
			if (resultCode == RESULT_OK) {
				Intent iCreate = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null,mContext, LockPatternActivity.class);
				startActivityForResult(iCreate, REQ_CREATE_PATTERN);
			}
			break;
		case REQ_CLEAR_PATTERN:
			if (resultCode == RESULT_OK) {
				AppLockManager.getInstance().getCurrentAppLock()
						.setPattern(null);
			}
			break;
		default:
			break;
		}
		updateUI();
	}

	private void updateUI() {
		if (mListLockType.getValue().toString().equals("1")) {
			changePass.setTitle(R.string.passcode_change_passcode);
			changePass.setSummary(R.string.passcode_change_passcode_summary);
			if (AppLockManager.getInstance().getCurrentAppLock().isPasswordLocked()) {
				turnPassOnOff.setTitle(R.string.passcode_turn_off);
				turnPassOnOff.setSummary(R.string.passcode_turn_off_summary);
				changePass.setEnabled(true);
				forgotPass.setEnabled(true);
			} else {
				turnPassOnOff.setTitle(R.string.passcode_turn_on);
				turnPassOnOff.setSummary(R.string.passcode_turn_on_summary);
				changePass.setEnabled(false);
				forgotPass.setEnabled(false);
			}
		} else {
			changePass.setTitle(R.string.pattern_change);
			changePass.setSummary(R.string.pattern_change_summary);
			if (AppLockManager.getInstance().getCurrentAppLock().isPatternLocked()) {
				turnPassOnOff.setTitle(R.string.pattern_turn_off);
				turnPassOnOff.setSummary(R.string.pattern_turn_off_summary);
				changePass.setEnabled(true);
				forgotPass.setEnabled(true);
			} else {
				turnPassOnOff.setTitle(R.string.pattern_turn_on);
				turnPassOnOff.setSummary(R.string.pattern_turn_on_summary);
				changePass.setEnabled(false);
				forgotPass.setEnabled(false);
			}
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private boolean checkAccount() {
		if (Constants.getAccount(mContext).equals(" ")) {
//			AccountManager acm = AccountManager.get(mContext);
//			acm.addAccount("com.google", "ah", null, new Bundle(), (Activity) mContext, null, null);
			((Activity) mContext).runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(	mContext,"Login an account Google", Toast.LENGTH_LONG).show();
				}
			});
			return false;
		} else {
			return true;
		}
	}

	private boolean checkWifi() {
		if (NetworkUtil.getConnectivityStatus(mContext) == 0) {
			// Do whatever
			((Activity) mContext).runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(	mContext,"Unable to connect to network. Check connect settings and try again", Toast.LENGTH_LONG).show();
				}
			});
			return false;
		} else {
			return true;
		}
	}

	private OnPreferenceChangeListener checkSyncContentsChangeListener = new OnPreferenceChangeListener() {

		@Override
		public boolean onPreferenceChange(Preference arg0, Object newValue) {
			// TODO Auto-generated method stub
			if (newValue.toString().equals("true")) {
				// Start Service
				Directory.createFolderBackup();
				if (checkWifi() && checkAccount()) {
					Intent mIntent = new Intent(mContext, ServiceBackup.class);
					mIntent.putExtra("URL_BACKUP", Constants.getUrl_Backup(mContext));
					mContext.startService(mIntent);
					((Activity) mContext).runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(mContext, "Starting Service Backup",
									Toast.LENGTH_LONG).show();
						}
					});
				} else {
					
				}
			} else {
				// stop Service
				Intent mIntent = new Intent(mContext, ServiceBackup.class);
				stopService(mIntent);
			}
			return true;
		}
	};

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		// TODO Auto-generated method stub
		if (key.equals(ANIMATION_SPEED_PREFERENCE_KEY)) {
			int value = sharedPreferences.getInt(ANIMATION_SPEED_PREFERENCE_KEY, 0);
			Toast.makeText(this, getString(R.string.summary, value),Toast.LENGTH_LONG).show();
		}

	}
}
